<template>
  <view class="login-container">
    <view class="login-header">
      <image class="logo" src="https://images.unsplash.com/photo-1619642751034-765dfdf7c58e?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=800&q=80" mode="aspectFit"></image>
      <text class="title">自助洗车系统</text>
    </view>
    
    <view class="login-form">
      <u-form :model="form" ref="uForm">
        <u-form-item label="手机号" prop="mobile">
          <u-input v-model="form.mobile" placeholder="请输入手机号" type="number" maxlength="11"></u-input>
        </u-form-item>
        
        <u-form-item label="验证码" prop="code">
          <u-input v-model="form.code" placeholder="请输入验证码" type="number" maxlength="6">
            <template #suffix>
              <u-button 
                type="primary" 
                size="mini" 
                :disabled="codeDisabled" 
                @click="sendCode"
              >
                {{ codeText }}
              </u-button>
            </template>
          </u-input>
        </u-form-item>
        
        <u-form-item>
          <u-button type="primary" @click="handleLogin" block>登录</u-button>
        </u-form-item>
      </u-form>
      
      <view class="register-link">
        <text @click="goToRegister">没有账号？立即注册</text>
      </view>
      
      <view class="agreement">
        <text class="agreement-text">登录即表示您同意</text>
        <text class="agreement-link" @click="showAgreement">《用户协议》</text>
        <text class="agreement-text">和</text>
        <text class="agreement-link" @click="showPrivacy">《隐私政策》</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'
import { sendSmsCode, login as userLogin } from '@/api/user'

// 表单数据
const form = reactive({
  mobile: '',
  code: ''
})

// 用户store
const userStore = useUserStore()

// 验证码相关
const codeText = ref('获取验证码')
const codeDisabled = ref(false)
let countdown = 60

// 表单验证规则
const rules = {
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: ['blur', 'change'] }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: ['blur', 'change'] },
    { pattern: /^\d{6}$/, message: '验证码格式不正确', trigger: ['blur', 'change'] }
  ]
}

const uForm = ref<any>(null)

// 发送验证码
const sendCode = async () => {
  if (!form.mobile) {
    uni.showToast({ title: '请输入手机号', icon: 'none' })
    return
  }
  
  // 验证手机号格式
  const mobileReg = /^1[3-9]\d{9}$/
  if (!mobileReg.test(form.mobile)) {
    uni.showToast({ title: '手机号格式不正确', icon: 'none' })
    return
  }
  
  // 调用API发送验证码
  uni.showLoading({ title: '发送中...' })
  try {
    const res = await sendSmsCode(form.mobile)
    uni.hideLoading()
    
    if (res.code === 200) {
      uni.showToast({ title: '验证码已发送', icon: 'success' })
      
      // 设置倒计时
      codeDisabled.value = true
      countdown = 60
      codeText.value = `${countdown}s后重新获取`
      
      const timer = setInterval(() => {
        countdown--
        if (countdown <= 0) {
          clearInterval(timer)
          codeDisabled.value = false
          codeText.value = '获取验证码'
        } else {
          codeText.value = `${countdown}s后重新获取`
        }
      }, 1000)
    } else {
      uni.showToast({ title: res.message, icon: 'none' })
    }
  } catch (error) {
    uni.hideLoading()
    uni.showToast({ title: '发送失败，请重试', icon: 'none' })
  }
}

// 登录
const handleLogin = () => {
  // 表单验证
  if (uForm.value) {
    uForm.value.validate().then(async () => {
      uni.showLoading({ title: '登录中...' })
      
      try {
        const res = await userLogin({
          mobile: form.mobile,
          code: form.code
        })
        
        uni.hideLoading()
        
        if (res.code === 200 && res.data) {
          // 保存用户信息到store
          userStore.setUserInfo(res.data.userInfo)
          
          uni.showToast({ title: '登录成功', icon: 'success' })
          
          // 跳转到首页
          uni.switchTab({ url: '/pages/index/index' })
        } else {
          uni.showToast({ title: res.message || '登录失败', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: '登录失败，请重试', icon: 'none' })
      }
    }).catch((errors: any) => {
      console.log('验证失败', errors)
    })
  }
}

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({ url: '/pages/register/register' })
}

// 显示用户协议
const showAgreement = () => {
  uni.showToast({ title: '用户协议', icon: 'none' })
}

// 显示隐私政策
const showPrivacy = () => {
  uni.showToast({ title: '隐私政策', icon: 'none' })
}

onMounted(() => {
  // 设置表单验证规则
  if (uForm.value) {
    uForm.value.setRules(rules)
  }
})

onLoad(() => {
  // 页面加载时的逻辑
})
</script>

<style lang="scss" scoped>
.login-container {
  padding: 40rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.login-header {
  text-align: center;
  margin-bottom: 80rpx;
  padding-top: 100rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 30rpx;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.login-form {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
}

.register-link {
  text-align: center;
  margin: 20rpx 0;
  
  text {
    color: #007aff;
    font-size: 28rpx;
  }
}

.agreement {
  text-align: center;
  margin-top: 30rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: #999;
}

.agreement-link {
  font-size: 24rpx;
  color: #007aff;
  margin: 0 10rpx;
}
</style>